package net.maergaiyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.maergaiyun.config.RabbitMQConfig;
import net.maergaiyun.controller.request.AccountLoginRequest;
import net.maergaiyun.controller.request.AccountRegisterRequest;
import net.maergaiyun.enums.AuthTypeEnum;
import net.maergaiyun.enums.BizCodeEnum;
import net.maergaiyun.enums.EventMessageType;
import net.maergaiyun.enums.SendCodeEnum;
import net.maergaiyun.interceptor.LoginInterceptor;
import net.maergaiyun.manager.AccountManager;
import net.maergaiyun.mapper.AccountMapper;
import net.maergaiyun.model.AccountDO;
import net.maergaiyun.model.EventMessage;
import net.maergaiyun.model.LoginUser;
import net.maergaiyun.service.AccountService;
import net.maergaiyun.service.NotifyService;
import net.maergaiyun.util.CommonUtil;
import net.maergaiyun.util.IDUtil;
import net.maergaiyun.util.JWTUtil;
import net.maergaiyun.util.JsonData;
import net.maergaiyun.vo.AccountVO;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AccountServiceImpl implements AccountService {
    @Autowired
    private NotifyService notifyService;

    @Autowired
    private AccountManager accountManager;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitMQConfig rabbitMQConfig;

    /**
     * 免费流量包商品id
     */
    private static final Long FREE_TRAFFIC_PRODUCT_ID = 1L;


    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public JsonData register(AccountRegisterRequest request) {
        boolean checkCode = false;
        if (StringUtils.isNotBlank(request.getPhone())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER, request.getPhone(), request.getCode());
        }

        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }

        AccountDO accountDO = new AccountDO();
        BeanUtils.copyProperties(request, accountDO);
        // 认证级别
        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());
        // TODO
        accountDO.setAccountNo(Long.valueOf(IDUtil.geneSnowFlakeID().toString()));
        accountDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
        String cryptPwd = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());
        accountDO.setPwd(cryptPwd);
        int rows = accountManager.insert(accountDO);
        log.info("注册成功, rows={}, accountDO={}", rows, accountDO);

        // 发放新用户注册福利
        userRegisterInitTask(accountDO);
        return JsonData.buildSuccess();
    }

    @Override
    public JsonData login(AccountLoginRequest request) {
        List<AccountDO> accountDOList = accountManager.findByPhone(request.getPhone());
        if (accountDOList != null && accountDOList.size() == 1) {
            AccountDO accountDO = accountDOList.get(0);
            String md5Crypt = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());
            if (md5Crypt.equalsIgnoreCase(accountDO.getPwd())) {
                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(accountDO, loginUser);
                String token = JWTUtil.geneJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);
            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }
        } else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    @Override
    public JsonData detail() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        AccountDO accountDO = accountManager.detail(loginUser.getAccountNo());
        AccountVO accountVO = new AccountVO();
        BeanUtils.copyProperties(accountDO, accountVO);
        return JsonData.buildSuccess(accountVO);
    }

    private void userRegisterInitTask(AccountDO accountDO) {

        EventMessage eventMessage = EventMessage.builder().messageId(IDUtil.geneSnowFlakeID().toString()).accountNo(accountDO.getAccountNo()).eventMessageType(EventMessageType.TRAFFIC_FREE_INIT.name()).bizId(FREE_TRAFFIC_PRODUCT_ID.toString()).build();

        rabbitTemplate.convertAndSend(rabbitMQConfig.getTrafficEventExchange(), rabbitMQConfig.getTrafficFreeInitRoutingKey(), eventMessage);
        log.info("发送新用户注册发放流量包福利消息: {}", eventMessage);
    }
}
